package com.cash.app.ui.other

import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant.FEEDBACK_SELECT_PHOTO_MAX
import com.cash.app.constant.AppConstant.PHONE_LENGTH
import com.cash.app.custom.AppActionBar
import com.cash.app.databinding.AcFeedbackSubmitBinding
import com.cash.app.ui.other.adapter.FeedbackPhotoAdapter
import com.cash.app.utils.ImagePickerUtils

class FeedbackSubmitActivity : BaseActivity() {

    private lateinit var binding: AcFeedbackSubmitBinding
    private val viewModel: FeedbackSubmitViewModel by viewModels()
    private val photoAdapter = FeedbackPhotoAdapter()
    private val selectedPhotos = mutableListOf<Uri>()
    private var isLoading = false

    override fun setViewBind() {
        binding = AcFeedbackSubmitBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun getAppActionBar(): AppActionBar? {
        return binding.actionBar
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setupViews()
        setupListeners()
        setupObservers()
    }

    override fun onBackPressed() {
        if (!isLoading) {
            super.onBackPressed()
        }
    }

    private fun setupObservers() {
        viewModel.submitSuccess.observe(this) {
            hideLoading()
            Toast.makeText(this, R.string.feedback_success, Toast.LENGTH_SHORT).show()
            finish()
        }

//        viewModel.isLoading.observe(this) { loading ->
//            isLoading = loading
//            if (loading) {
//                showLoading()
//            } else {
//                hideLoading()
//            }
//        }
    }

    private fun showLoading() {
        binding.loadingLayout.visibility = View.VISIBLE
    }

    private fun hideLoading() {
        binding.loadingLayout.visibility = View.GONE
    }

    private val imagePicker = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            showLoading()
            val newPhotos = ImagePickerUtils.handleImagePickerResult(
                result.data, FEEDBACK_SELECT_PHOTO_MAX - selectedPhotos.size
            )
            if (newPhotos.isNotEmpty()) {
                selectedPhotos.addAll(newPhotos)
                photoAdapter.updatePhotos(selectedPhotos)
            }
            hideLoading()
        }
    }

    private fun setupViews() {
        binding.rvPhotos.apply {
            layoutManager = LinearLayoutManager(
                this@FeedbackSubmitActivity, LinearLayoutManager.HORIZONTAL, false
            )
            adapter = photoAdapter
        }
    }

    private fun setupListeners() {
        photoAdapter.onDeleteClick = { position ->
            selectedPhotos.removeAt(position)
            photoAdapter.updatePhotos(selectedPhotos)
        }

        binding.btnAddPhoto.setOnClickListener {
            if (selectedPhotos.size < FEEDBACK_SELECT_PHOTO_MAX) {
                imagePicker.launch(ImagePickerUtils.getImagePickerIntent())
            } else {
                Toast.makeText(
                    this, getString(R.string.photo_limit_3), Toast.LENGTH_SHORT
                ).show()
            }
        }

        binding.btnSubmit.setOnClickListener {
            if (validateInput()) {
                showLoading()
                submitFeedback()
            }
        }

        binding.cbPayment.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) binding.cbOther.isChecked = false
        }

        binding.cbOther.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) binding.cbPayment.isChecked = false
        }
    }

    private fun validateInput(): Boolean {
        val phone = binding.etPhoneNumber.text.toString()
        val feedback = binding.etFeedback.text.toString()

        if (phone.length != PHONE_LENGTH) {
            Toast.makeText(this, R.string.login_tip_phone_2, Toast.LENGTH_SHORT).show()
            return false
        }

        if (feedback.length < PHONE_LENGTH) {
            Toast.makeText(
                this, R.string.feedback_hint, Toast.LENGTH_SHORT
            ).show()
            return false
        }
        return true
    }

    private fun submitFeedback() {
        viewModel.submitFeedback(
            this,
            phoneNumber = binding.etPhoneNumber.text.toString(),
            content = binding.etFeedback.text.toString(),
            photos = selectedPhotos
        )
    }
}